import React from "react";
import { useNavigate } from "react-router-dom";
import { useI18n, toApiLanguageCode } from '@/utils/in18';
import { request } from '@/utils/request';
import axios from 'axios';
import { getStoredBearerToken, hasStoredToken } from '@/utils/auth';
import { openLoginModal, setLoginReturnState } from '@/componets/loginModel';

type Props = {
  visible: boolean;
  onClose: () => void;
  card?: {
    id: number;
    title: string;
    desc?: string;
    src?: string;
    raw?: any;
    role_prompt: any;
  } | null;
};

const InformationCardPC: React.FC<Props> = ({ visible, onClose, card = null }) => {
  const navigate = useNavigate();
  const { t, locale } = useI18n();

  const [works, setWorks] = React.useState<any[]>([]);
  const [page, setPage] = React.useState<number>(1);
  const [pageSize] = React.useState<number>(12);
  const [loading, setLoading] = React.useState<boolean>(false);
  const [noMore, setNoMore] = React.useState<boolean>(false);
  const [noUserGenerated, setNoUserGenerated] = React.useState<boolean>(false);

  const [likesState, setLikesState] = React.useState<Record<number, { liked: boolean; count: number }>>({});
  const [gridLoadedMap, setGridLoadedMap] = React.useState<Record<number, boolean>>({});

  const [previewOpen, setPreviewOpen] = React.useState<boolean>(false);
  const [previewIndex, setPreviewIndex] = React.useState<number>(0);

  // 角色详情描述（从 /api/template/getRoleDetailRoute 获取）
  const [roleDescription, setRoleDescription] = React.useState<string>('');

  // 打开时请求角色详情
  React.useEffect(() => {
    if (!visible || !card) return;
    try {
      const templateId = card?.raw?.id ?? card?.id ?? 0;
      if (!templateId) return;
      request
        .post('/api/template/getRoleDetailRoute', { id: templateId })
        .then((res) => {
          try {
            const desc = res?.data?.data?.description;
            if (typeof desc === 'string') {
              let parsed: any = null;
              try { parsed = JSON.parse(desc); } catch {}
              if (parsed && typeof parsed === 'object' && typeof parsed.PersonalProfile !== 'undefined') {
                setRoleDescription(String(parsed.PersonalProfile));
              } else {
                setRoleDescription(desc);
              }
            } else if (desc && typeof desc === 'object' && typeof (desc as any).PersonalProfile !== 'undefined') {
              setRoleDescription(String((desc as any).PersonalProfile));
            }
          } catch {}
        })
        .catch(() => {});
    } catch {}
  }, [visible, card]);

  const previewList = React.useMemo(() => {
    const list: { id: string | number; src: string }[] = [];
    try {
      works.forEach((w) => { if (w?.src) list.push({ id: w.id, src: String(w.src) }); });
    } catch { }
    return list;
  }, [works]);

  const openPreviewAt = (index: number) => {
    if (!previewList.length) return;
    const safeIndex = Math.max(0, Math.min(index, previewList.length - 1));
    setPreviewIndex(safeIndex);
    setPreviewOpen(true);
  };
  const openPreviewById = (targetId: string | number) => {
    if (!previewList.length) return;
    const idx = previewList.findIndex((p) => String(p.id) === String(targetId));
    openPreviewAt(idx >= 0 ? idx : 0);
  };
  const closePreview = () => setPreviewOpen(false);
  const goPrev = () => { if (previewList.length) setPreviewIndex((i) => (i - 1 + previewList.length) % previewList.length); };
  const goNext = () => { if (previewList.length) setPreviewIndex((i) => (i + 1) % previewList.length); };

  React.useEffect(() => {
    if (!previewOpen) return;
    const onKey = (e: KeyboardEvent) => {
      try {
        if (e.key === 'ArrowLeft') { e.preventDefault(); goPrev(); }
        else if (e.key === 'ArrowRight') { e.preventDefault(); goNext(); }
        else if (e.key === 'Escape') { e.preventDefault(); closePreview(); }
      } catch { }
    };
    window.addEventListener('keydown', onKey as any);
    return () => { try { window.removeEventListener('keydown', onKey as any); } catch { } };
  }, [previewOpen, previewList.length]);

  // 登录回跳后：根据保存的状态滚动到指定的作品位置
  const containerRef = React.useRef<HTMLDivElement | null>(null);
  React.useEffect(() => {
    try {
      const raw = sessionStorage.getItem('login:return_state');
      if (!raw) return;
      const state = JSON.parse(raw);
      if (state?.type !== 'infoCardPC') return;
      const targetId = state?.restoreScrollToId;
      if (!targetId) return;
      const tryScroll = () => {
        try {
          const container = containerRef.current;
          if (!container) return;
          const el = container.querySelector(`[data-work-id="${String(targetId)}"]`);
          if (el && (el as any).scrollIntoView) {
            (el as any).scrollIntoView({ behavior: 'smooth', block: 'center' });
            sessionStorage.removeItem('login:return_state');
          }
        } catch { }
      };
      requestAnimationFrame(() => requestAnimationFrame(tryScroll));
      setTimeout(tryScroll, 500);
    } catch { }
  }, [works, visible]);

  const toggleLike = async (id: number) => {
    if (!hasStoredToken()) {
      try { setLoginReturnState({ type: 'infoCardPC', url: window.location.href, templateCard: card, restoreScrollToId: id }); } catch { }
      try { openLoginModal(); } catch { }
      return;
    }
    const prevEntry = likesState[id] || { liked: false, count: 0 };
    setLikesState((prev) => {
      const cur = prev[id] || { liked: false, count: 0 };
      const newLiked = !cur.liked;
      const newCount = cur.count + (newLiked ? 1 : -1);
      return { ...prev, [id]: { liked: newLiked, count: newCount } };
    });
    try {
      const authHeader = getStoredBearerToken();
      if (!authHeader) {
        setLikesState((prev) => ({ ...prev, [id]: prevEntry }));
        try { setLoginReturnState({ type: 'infoCardPC', url: window.location.href, templateCard: card, restoreScrollToId: id }); } catch { }
        try { openLoginModal(); } catch { }
        return;
      }
      const langCode = toApiLanguageCode(locale as any);
      const apiBase = (import.meta as any).env?.VITE_API || '';
      const res = await axios.post(`${apiBase}/api/work/toggleWorkLikeRoute`, { work_id: id, language: langCode }, { headers: { Authorization: authHeader } });
      if (res?.data?.success === true) {
        const d = res.data.data || {};
        const isLiked = typeof d.is_liked !== 'undefined' ? d.is_liked : (typeof d.isLiked !== 'undefined' ? d.isLiked : undefined);
        const likesCount = typeof d.likes_count !== 'undefined' ? d.likes_count : (typeof d.likesCount !== 'undefined' ? d.likesCount : undefined);
        setLikesState((prev) => {
          const base = prev[id] || prevEntry;
          return { ...prev, [id]: { liked: typeof isLiked !== 'undefined' ? !!isLiked : base.liked, count: typeof likesCount !== 'undefined' ? Number(likesCount) : base.count } };
        });
      } else {
        setLikesState((prev) => ({ ...prev, [id]: prevEntry }));
        try { console.log(res?.data?.msg || t('home.operation_failed')); } catch { }
      }
    } catch (e) {
      setLikesState((prev) => ({ ...prev, [id]: prevEntry }));
      try { console.log(t('home.network_error')); } catch { }
    }
  };

  const fetchWorks = async (pageToLoad: number, replace = false) => {
    if (!card) return;
    if (loading) return;
    setLoading(true);
    try {
      const templateId = card?.raw?.id ?? card?.id ?? 0;
      const langCode = toApiLanguageCode(locale as any);
      const raw = localStorage.getItem('userData');
      const parsed = raw ? JSON.parse(raw) : null;
      const token = parsed?.user_token;
      let res;
      if (token) {
        const authHeader = typeof token === 'string' && token.trim().toLowerCase().startsWith('bearer ') ? token : `Bearer ${token}`;
        res = await request.post('/api/template/getPublicWorksByTemplateRoute', {
          template_id: templateId,
          sort: 'likes',
          page: pageToLoad,
          page_size: pageSize,
          language: langCode,
        }, { headers: { Authorization: authHeader } });
      } else {
        res = await request.post('/api/template/getPublicWorksByTemplateRoute', {
          template_id: templateId,
          sort: 'likes',
          page: pageToLoad,
          page_size: pageSize,
          language: langCode,
        });
      }
      if (res?.data?.success === true) {
        const data = Array.isArray(res.data.data) ? res.data.data : [];
        if (pageToLoad === 1 && data.length === 0) {
          setNoUserGenerated(true);
        } else if (replace) {
          setNoUserGenerated(false);
        }
        const mapped = data.map((it: any) => ({
          id: it.id,
          src: it.image_url,
          likes: it.likes_count,
          userName: it.creator?.nickname || '',
          avatar: it.creator?.avatar_url || '',
          raw: it,
        }));
        setWorks((prev) => (replace ? mapped : prev.concat(mapped)));
        setLikesState((prev) => {
          const next = { ...prev };
          mapped.forEach((it: any) => { next[it.id] = { liked: !!it.raw?.is_liked, count: Number(it.raw?.likes_count ?? it.likes ?? 0) }; });
          return next;
        });
        setGridLoadedMap((prev) => {
          const next = { ...prev };
          mapped.forEach((it: any) => { if (typeof next[it.id] === 'undefined') next[it.id] = false; });
          return next;
        });
        const returnedPage = Number(res.data.page || pageToLoad);
        const returnedPageSize = Number(res.data.page_size || pageSize);
        const returnedTotal = Number(res.data.total || 0);
        setPage(returnedPage);
        if (data.length === 0 || (returnedTotal > 0 && returnedPage * returnedPageSize >= returnedTotal)) {
          setNoMore(true);
        } else {
          setNoMore(false);
        }
      }
    } catch (e) {
      // ignore
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => {
    if (!visible || !card) return;
    setWorks([]);
    setPage(1);
    setNoMore(false);
    fetchWorks(1, true);
  }, [card, visible, locale]);

  React.useEffect(() => {
    const el = containerRef.current;
    if (!el) return;
    const onScroll = () => {
      try {
        if (loading || noMore || !visible) return;
        const scrollTop = el.scrollTop;
        const clientHeight = el.clientHeight;
        const scrollHeight = el.scrollHeight;
        if (scrollTop + clientHeight >= scrollHeight - 200) {
          fetchWorks(page + 1, false);
        }
      } catch { }
    };
    el.addEventListener('scroll', onScroll, { passive: true } as any);
    return () => { try { el.removeEventListener('scroll', onScroll as any); } catch { } };
  }, [page, loading, noMore, visible]);

  return (
    <div
      className={`fixed inset-0 z-[100100] ${visible ? 'pointer-events-auto' : 'pointer-events-none'}`}
      aria-hidden={!visible}
    >
      <div
        onClick={onClose}
        className={`absolute inset-0 bg-black/50 transition-opacity ${visible ? 'opacity-100' : 'opacity-0'}`}
      />

      <div className={`absolute inset-0 flex items-center justify-center`}>
        <div
          className={`w-full max-w-[1200px] bg-[#F5F5F5] dark:bg-gray-800 shadow-2xl rounded-xl transform transition-transform ${visible ? 'scale-100' : 'scale-95'}`}
          style={{ height: '82vh' }}
        >
          <div className="relative h-full flex flex-col">
            <button
              aria-label="close"
              onClick={onClose}
              className="absolute right-3 top-3 p-2 rounded-full bg-white/70 dark:bg-black/40 hover:bg-white/90 dark:hover:bg-black/60 text-gray-700 dark:text-gray-200"
            >
              <svg viewBox="0 0 1024 1024" width="22" height="22" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M512 469.333l226.133-226.133 42.667 42.667L554.667 512l226.133 226.133-42.667 42.667L512 554.667 285.867 780.8l-42.667-42.667L469.333 512 243.2 285.867l42.667-42.667L512 469.333z" /></svg>
            </button>

            <div className="px-6 pr-16 pt-6 pb-3 border-b border-gray-200 dark:border-gray-700">
              <div className="flex items-start justify-between gap-4">
                <div className="min-w-0">
                  <h1 className="text-2xl font-bold text-gray-800 dark:text-gray-100">{t('informationCard.image_list')}</h1>
                  {card ? (
                    <div className="mt-1">
                      <div className="text-sm text-gray-500 dark:text-gray-300 font-semibold">{card.title}</div>
                      {(roleDescription || card.desc) ? (
                        <div className="mt-1 text-sm text-gray-600 dark:text-gray-300 text-left">
                          {roleDescription || card.desc}
                        </div>
                      ) : null}
                    </div>
                  ) : null}
                </div>
                <div className="shrink-0">
                  <button
                    onClick={() => {
                      try { onClose(); } catch { }
                      try { navigate('/CreateImage', { state: { id: card?.id, name: card?.title, image_url: card?.src, role_prompt: card?.role_prompt || card?.raw?.role_prompt, category: card?.raw?.category || (card as any)?.category } }); } catch { }
                    }}
                    className="bg-primary dark:bg-[#0A0907] text-white px-5 py-2 rounded-md shadow hover:opacity-90"
                  >{t('informationCard.make_image')}</button>
                </div>
              </div>
            </div>

            <div ref={containerRef} className="flex-1 overflow-y-auto px-6 py-4" onClick={(e) => { e.stopPropagation(); }}>
              <div className='grid gap-3 grid-cols-3 md:grid-cols-4 lg:grid-cols-6'>
                {noUserGenerated && !loading ? (
                  <div className="col-span-full text-center text-gray-500 dark:text-gray-300 py-10">{t('informationCard.no_user_generated_images')}</div>
                ) : (
                  works.map((item) => (
                    <div key={item.id} data-work-id={item.id} className="dark:bg-[#2c2c2c] border border-transparent hover:border-gray-200 dark:hover:border-gray-700 bg-white rounded-lg overflow-hidden shadow-sm transition-colors">
                      <div className="relative bg-gray-50 dark:bg-[#111]" style={{ paddingBottom: '167.1875%' }}>
                        {!gridLoadedMap[item.id] && (
                          <div className="absolute inset-0 bg-gray-200 dark:bg-gray-700 animate-pulse" />
                        )}
                        <img
                          src={item.src || ''}
                          alt={item.userName || 'no image'}
                          className="absolute inset-0 w-full h-full object-cover cursor-zoom-in"
                          onLoad={() => setGridLoadedMap((prev) => ({ ...prev, [item.id]: true }))}
                          onError={() => setGridLoadedMap((prev) => ({ ...prev, [item.id]: true }))}
                          onClick={() => openPreviewById(item.id)}
                        />
                      </div>
                      <div className="flex justify-between items-center px-3 py-2 dark:bg-[#1c1c1c] bg-white">
                        <p className="text-gray-600 dark:text-gray-300 text-sm truncate mr-2" title={item.userName}>{item.userName}</p>
                        <button onClick={() => toggleLike(item.id)} className="text-gray-500 dark:text-white flex items-center">
                          {!likesState[item.id]?.liked ? (
                            <svg viewBox="0 0 1024 1024" width="18" height="18" xmlns="http://www.w3.org/2000/svg" className="fill-current"><path d="M667.786667 117.333333C832.864 117.333333 938.666667 249.706667 938.666667 427.861333c0 138.250667-125.098667 290.506667-371.573334 461.589334a96.768 96.768 0 0 1-110.186666 0C210.432 718.368 85.333333 566.112 85.333333 427.861333 85.333333 249.706667 191.136 117.333333 356.213333 117.333333c59.616 0 100.053333 20.832 155.786667 68.096C567.744 138.176 608.170667 117.333333 667.786667 117.333333z m0 63.146667c-41.44 0-70.261333 15.189333-116.96 55.04-2.165333 1.845333-14.4 12.373333-17.941334 15.381333a32.32 32.32 0 0 1-41.770666 0c-3.541333-3.018667-15.776-13.536-17.941334-15.381333-46.698667-39.850667-75.52-55.04-116.96-55.04C230.186667 180.48 149.333333 281.258667 149.333333 426.698667 149.333333 537.6 262.858667 675.242667 493.632 834.826667a32.352 32.352 0 0 0 36.736 0C761.141333 675.253333 874.666667 537.6 874.666667 426.698667c0-145.44-80.853333-246.218667-206.88-246.218667z" /></svg>
                          ) : (
                            <svg viewBox="0 0 1024 1024" width="18" height="18" xmlns="http://www.w3.org/2000/svg"><path d="M512 901.746939c-13.583673 0-26.122449-4.179592-37.093878-13.061225-8.881633-7.314286-225.697959-175.020408-312.424489-311.379592C133.746939 532.37551 94.040816 471.24898 94.040816 384.522449c0-144.718367 108.146939-262.269388 240.326531-262.269388 67.395918 0 131.657143 30.82449 177.632653 84.636735 45.453061-54.334694 109.191837-84.636735 177.110204-84.636735 132.702041 0 240.326531 117.55102 240.326531 262.269388 0 85.159184-37.093878 143.673469-67.395919 191.216327l-1.044898 1.567346c-86.726531 136.359184-303.542857 304.587755-312.424489 311.379592-10.44898 8.359184-22.987755 13.061224-36.571429 13.061225z" fill="#E5404F" /></svg>
                          )}
                          <span className="text-gray-500 dark:text-gray-300 ml-1 text-sm">{likesState[item.id]?.count ?? item.likes}</span>
                        </button>
                      </div>
                    </div>
                  ))
                )}
              </div>
              <div className='w-full flex items-center justify-center py-4 text-sm text-gray-400'>
                {loading ? t('home.loading') : (noMore ? t('home.no_more') : '')}
              </div>
            </div>

          </div>
        </div>
      </div>

      {previewOpen && (
        <div
          className="fixed inset-0 z-[100101] bg-black/80 flex items-center justify-center pointer-events-auto"
          onClick={closePreview}
          onWheel={(e) => { try { e.stopPropagation(); e.preventDefault(); } catch { } }}
          onTouchMove={(e) => { try { e.stopPropagation(); e.preventDefault(); } catch { } }}
        >
          <div className="relative max-w-[94vw] max-h-[88vh]" onClick={(e) => { e.stopPropagation(); }}>
            <img
              src={previewList[previewIndex]?.src || ''}
              alt={String(previewList[previewIndex]?.id || '')}
              className="object-contain max-w-[94vw] max-h-[88vh] rounded"
            />
            <button
              aria-label="prev"
              onClick={(e) => { e.stopPropagation(); goPrev(); }}
              className="absolute left-2 top-1/2 -translate-y-1/2 p-2 rounded-full bg-white/20 hover:bg-white/30 text-white"
            >
              <svg viewBox="0 0 1024 1024" width="24" height="24" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M640 896c-8.192 0-16.384-3.072-22.656-9.344L320 589.312 320 640c0 17.664-14.336 32-32 32S256 657.664 256 640L256 448c0-0.64 0.064-1.28 0.096-1.92 0.032-0.704 0.064-1.408 0.16-2.112 0.256-2.112 0.672-4.16 1.248-6.144 0.192-0.64 0.256-1.344 0.512-1.984 0.064-0.128 0.064-0.256 0.128-0.384 0.96-2.24 2.176-4.352 3.584-6.336 0.32-0.448 0.512-0.96 0.832-1.408 0.192-0.256 0.448-0.448 0.64-0.704 0.512-0.64 1.024-1.28 1.6-1.92 0.448-0.512 0.832-1.024 1.28-1.536 0.384-0.448 0.768-0.896 1.216-1.28 0.384-0.384 0.8-0.768 1.216-1.152 0.512-0.448 0.96-0.96 1.536-1.344l0.32-0.192c0.576-0.448 1.216-0.768 1.792-1.152 0.64-0.384 1.216-0.832 1.888-1.152 0.64-0.32 1.344-0.512 1.984-0.768 2.048-0.768 4.16-1.28 6.336-1.536 0.64-0.064 1.28-0.256 1.92-0.256 0.832-0.064 1.664-0.064 2.56-0.064l192 0c17.664 0 32 14.336 32 32s-14.336 32-32 32L391.04 384 640 632.96c12.512 12.512 12.512 32.832 0 45.312C656.384 892.928 648.192 896 640 896z" /></svg>
            </button>
            <button
              aria-label="next"
              onClick={(e) => { e.stopPropagation(); goNext(); }}
              className="absolute right-2 top-1/2 -translate-y-1/2 p-2 rounded-full bg-white/20 hover:bg-white/30 text-white"
            >
              <svg viewBox="0 0 1024 1024" width="24" height="24" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M384 896c-8.192 0-16.384-3.072-22.656-9.344-12.512-12.512-12.512-32.832 0-45.312L609.024 593.664 384 368.64c-12.512-12.512-12.512-32.832 0-45.312s32.832-12.512 45.312 0l248.96 248.96c12.512 12.512 12.512 32.832 0 45.312l-256 256C400.384 892.928 392.192 896 384 896z" /></svg>
            </button>
            <button
              aria-label="close"
              onClick={(e) => { e.stopPropagation(); closePreview(); }}
              className="absolute -top-10 right-0 p-2 rounded-full bg-white/20 hover:bg-white/30 text-white"
            >
              <svg viewBox="0 0 1024 1024" width="22" height="22" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M512 469.333l226.133-226.133 42.667 42.667L554.667 512l226.133 226.133-42.667 42.667L512 554.667 285.867 780.8l-42.667-42.667L469.333 512 243.2 285.867l42.667-42.667L512 469.333z" /></svg>
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default InformationCardPC;


